<?php

class IndexController extends Core_Controller_Action 
{
	public $newsLimit = 12;
	
	public $manuLimit = 12;
	
	public $itemsLimit = 12;
	
	public $menuType = 0;
	
	public $menu = array(
		'pl' => array(
			array(
				'name' => "Poorboy's World",
				'id' => 1,
				'url' => 'index'
			),
			array(
				'name' => 'Produkty',
				'id' => 2,
				'url' => 'shop'
			),
			array(
				'name' => 'Usługi',
				'id' => 3,
				'url' => 'services'
			),
			array(
				'name' => 'Współpraca',
				'id' => 4,
				'url' => 'cooperation'
			),
			array(
				'name' => 'Klub Carnauba',
				'id' => 5,
				'url' => 'club'
			),
			array(
				'name' => 'Akademia autodetailingu',
				'id' => 6,
				'url' => 'academy'
			),
			array(
				'name' => 'Kontakt',
				'id' => 7,
				'url' => 'contact'
			)
		),
		'en' => array(
			array(
				'name' => "Poorboy's World",
				'id' => 1,
				'url' => 'index'
			),
			array(
				'name' => 'Products',
				'id' => 2,
				'url' => 'shop'
			),
			array(
				'name' => 'Services',
				'id' => 3,
				'url' => 'services'
			),
			array(
				'name' => 'Współpraca',
				'id' => 4,
				'url' => 'cooperation'
			),
			array(
				'name' => 'Klub Carnauba',
				'id' => 5,
				'url' => 'club'
			),
			array(
				'name' => 'Akademia autodetailingu',
				'id' => 6,
				'url' => 'academy'
			),
			array(
				'name' => 'Kontakt',
				'id' => 7,
				'url' => 'contact'
			)
		),
		'cs' => array(
			array(
				'name' => "Poorboy's World",
				'id' => 1,
				'url' => 'index'
			),
			array(
				'name' => 'Obchod',
				'id' => 2,
				'url' => 'shop'
			),
			array(
				'name' => 'Služby',
				'id' => 3,
				'url' => 'services'
			),
			array(
				'name' => 'Współpraca',
				'id' => 4,
				'url' => 'cooperation'
			),
			array(
				'name' => 'Klub Carnauba',
				'id' => 5,
				'url' => 'club'
			),
			array(
				'name' => 'Akademia autodetailingu',
				'id' => 6,
				'url' => 'academy'

			),
			array(
				'name' => 'Kontakt',
				'id' => 7,
				'url' => 'contact'
			)
		) 
	);
	
	public function init() {
		$this->view->menuType = $this->menuType;
		$this->view->menuStatic = true;
	}
	
	public function authAction() {
		if( $this->_request->isPost() ) {
			$adapter = new Core_Auth_Adapter($this->_getParam('email'), md5( $this->_getParam('password') ) );
	        $result = Zend_Auth::getInstance()->authenticate($adapter);
	        if( Zend_Auth::getInstance()->hasIdentity() ) {
	        	$this->_redirect( 'index' );
	        }
		}
	}
	
	public function indexAction() {
		
		$this->_redirect( 'shop' );
		$News = new News();
		
//		$this->view->newsList = $News->getListService( 1, 1, true );
//		$this->view->newsList2 = $News->getListService( 2, 1, true );
//		$this->view->newsList3 = $News->getListService( 3, 1, true );
//
//		$miotaczUslugi = $News->getItemBySpeciesId( 11 )->getFirst();
//		$this->view->gelleryiduslugi = $miotaczUslugi->galeries_g_id;
//
//		$miotaczSklep = $News->getItemBySpeciesId( 10 )->getFirst();
//		$this->view->gelleryidsklep = $miotaczSklep->galeries_g_id;
		
	}
	
	public function p404Action() {
		
	}
	
	public function headerAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
		$userAction = $this->_request->getParam( 'c' );
		$ac = $this->_request->getParam( 'a' );
		$active = 1;
		
//		var_dump( $this->_request->getParam( 'c' ) );
//		var_dump( $this->_request->getParam( 'a' ) );
//		die(1);
		
		$logged = $this->_request->getParam( 'logged', 0 );
		$name = $this->_request->getParam( 'name', '' );
		$requestUri = str_replace( ' ', '/', $this->_request->getParam( 'r', '' ) );

		$xml = '﻿<?xml version="1.0" encoding="UTF-8"?>';
			$xml .= '<navigator>';
				$xml .= '<langs>';
					
					$xml .= '<item name="PL" id="0" url="' . $requestUri . '?lang=pl" />';
					$xml .= '<item name="ENG" id="1" url="' . $requestUri . '?lang=en" />';
					$xml .= '<item name="CZ" id="2" url="' . $requestUri . '?lang=cs" />';
					
					$xml .= '<active>' . $this->_loc2act( $this->locale ) . '</active>';
					
				$xml .= '</langs>';
				
				$xml .= '<menu>';
					foreach( $this->menu[$this->locale] as $value ) {

						if( $userAction == $value['url'] ) {
							$active = $value['id'];
						}
						
						if( $ac == 'search' ) {
							$active = 2;
						}
						
						$xml .= '<item name="' . $value['name'] . '" id ="' . $value['id'] . '" url="' . $this->view->baseUrl() . '/' . $value['url'] . '" />';
					}			
					$xml .= '<active>' . $active . '</active>';
				$xml .= '</menu>';

				$xml .= '<user>';
					$xml .= '<logged>' . $logged . '</logged>';
					$xml .= '<item name="' . $name . '"/>';
				$xml .= '</user>';
				
				$xml .= '<images>';
					
				$header = new Header();
				$list = $header->getItemByCategory($active);
				
				$header_item = array();
		
				for($i=0;$i<12;$i++) $header_item[$i] = "";
					
					
				for($i=0;$i < count($list);$i++)
				{
				$header_item[$list[$i]['number']-1] = $list[$i]['img'];
				}

			
				
					$xml .= '<item id="1" part1="' . $this->view->baseUrl() . '/public/uploads/' .(isset($header_item[0]) ? $header_item[0] : '') . '" part2="' . $this->view->baseUrl() . '/public/uploads/' . (isset($header_item[1]) ? $header_item[1] : '') . '" part3="' . $this->view->baseUrl() . '/public/uploads/' . (isset($header_item[2]) ? $header_item[2] : '') . '" />';
					$xml .= '<item id="2" part1="' . $this->view->baseUrl() . '/public/uploads/' .(isset($header_item[3]) ? $header_item[3] : '') . '" part2="' . $this->view->baseUrl() . '/public/uploads/' . (isset($header_item[4]) ? $header_item[4] : '') . '" part3="' . $this->view->baseUrl() . '/public/uploads/' . (isset($header_item[5]) ? $header_item[5] : '') . '" />';
					$xml .= '<item id="3" part1="' . $this->view->baseUrl() . '/public/uploads/' .(isset($header_item[6]) ? $header_item[6] : '') . '" part2="' . $this->view->baseUrl() . '/public/uploads/' . (isset($header_item[7]) ? $header_item[7] : '') . '" part3="' . $this->view->baseUrl() . '/public/uploads/' . (isset($header_item[8]) ? $header_item[8] : '') .  '" />';
					$xml .= '<item id="4" part1="' . $this->view->baseUrl() . '/public/uploads/' .(isset($header_item[9]) ? $header_item[9] : '') . '" part2="' . $this->view->baseUrl() . '/public/uploads/' . (isset($header_item[10]) ? $header_item[10] : '') . '" part3="' . $this->view->baseUrl() . '/public/uploads/' . (isset($header_item[11]) ? $header_item[11] : '') . '" />';
					
					
					/*$xml .= '<item id="1" part1="' . $this->view->baseUrl() . '/public/uploads/testoweLove00.png" part2="' . $this->view->baseUrl() . '/public/uploads/testoweLove01.png" part3="' . $this->view->baseUrl() . '/public/uploads/testoweLove02.png" />';
					$xml .= '<item id="2" part1="' . $this->view->baseUrl() . '/public/uploads/testoweLove11.jpg" part2="' . $this->view->baseUrl() . '/public/uploads/testoweLove12.jpg" part3="' . $this->view->baseUrl() . '/public/uploads/testoweLove13.jpg" />';
					$xml .= '<item id="3" part1="' . $this->view->baseUrl() . '/public/uploads/testoweLove13.jpg" part2="' . $this->view->baseUrl() . '/public/uploads/testoweLove13.jpg" part3="' . $this->view->baseUrl() . '/public/uploads/testoweLove13.jpg" />';
					$xml .= '<item id="4" part1="' . $this->view->baseUrl() . '/public/uploads/testoweLove00.png" part2="' . $this->view->baseUrl() . '/public/uploads/testoweLove01.png" part3="' . $this->view->baseUrl() . '/public/uploads/testoweLove02.png" />';*/
					
				$xml .= '</images>';
				
			$xml .= '</navigator>';
		
		$this->getResponse()->setHeader( 'Content-type', 'text/xml' );
		echo $xml;
	}

	public function putterAction() {
		$this->_helper->layout->disableLayout();

		$this->_helper->viewRenderer->setNoRender();
		
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		
		$Photos = new Photos();
		$items = $Photos->getListService( $id );

		$xml = '﻿<?xml version="1.0" encoding="UTF-8"?>';
			$xml .= '<images>';
				foreach( $items->toArray() as $value ) {
					$xml .= '<item img_path="' . $this->view->File( $value['iden'], 643 ) . '" thumb_path="' . $this->view->File( $value['iden'], 112 ) . '" img_description="' . $value['description_' . $this->locale] . '" />';
				}
			$xml .= '</images>';

		$this->getResponse()->setHeader( 'Content-type', 'text/xml' );
		echo $xml;
	}
	
	public function manufacturersxmlAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
	
		$locale = $this->_request->getParam( 'locale', 'pl' );
	
		$Manufacturers = new Manufacturers();
		$items = $Manufacturers->getListService();
		$i = 0;
		$xml = '﻿<?xml version="1.0" encoding="UTF-8"?>';
			$xml .= '<manufacturers>';
				foreach( $items->toArray() as $value ) {
					$xml .= '<item name="'. $value['name_' . $locale] .'" id="' . $i . '" img_path="' . $this->view->File( $value['logo'], 170 ) . '" url="' . $this->view->baseUrl() . '/shop/producer/id/' . $value['m_id'] . '/' . $this->view->Seo( $value['name_' . $locale] ) . '"/>';
					$i++;
				}
				$xml .= '<active>0</active>';
			$xml .= '</manufacturers>';

		$this->getResponse()->setHeader( 'Content-type', 'text/xml' );
		echo $xml;
	}
	
	public function movieAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		
		if( $id > 0 ) {
			$News = new News();
			
			$item = $News->getItemService( $id )->getFirst();
			
			$xml  = '<?xml version="1.0" encoding="UTF-8"?>';
			$xml .= '<videos>';
				$xml .= '<item video_path="' . $this->view->baseUrl() . '/public/uploads/' . $item->mov . '" thumb_path="files/video.jpg" video_description="' . $item['title_pl'] . '" />';
			$xml .= '</videos>';

			$this->getResponse()->setHeader( 'Content-type', 'text/xml' );
			echo $xml;
		}
	}
	
	public function manufacturersAction() 
	{
		$page = intval( $this->_request->getParam( 'page', 1 ) );
		$type = intval( $this->_request->getParam( 'type', 2 ) );
		
		$this->view->type = $type;
		$this->view->active = 'index/manufacturers/type/' . $type;
		
		$Manufacturers = new Manufacturers();
		
		$this->view->list = $Manufacturers->getList()->toArray();
		
		/*
		$pager = $Manufacturers->getListWithPagerService( $page, $this->manuLimit, $this->view->baseUrl() . '/index/manufacturers/page/{%page_number}/'  );

		
		$pagerLayout = $pager['layout'];
		$pagerLayout->setTemplate('<a class="nums" href="{%url}">{%page}</a>');
		$pagerLayout->setSelectedTemplate('<a class="nums focus" href="{%url}">{%page}</a>');
		
		$pager = $pager['pager'];

		$this->view->list = $pagerLayout->execute();
		$this->view->pager = $pagerLayout;
		
		$this->view->result = $pager->getNumResults();

		$this->view->page = $page;
		$this->view->pathInfo = $this->view->baseUrl() . $this->_request->getPathInfo();
		$this->view->limit = $this->manuLimit;
		*/	
	
	}

	public function paymentAction() {

		$req = 'cmd=_notify-synch';
		
		$tx_token = $_GET['tx'];
		$auth_token = "TLPpI3tQyK778h-6urDiInlcfYyQ4n5tvfMCmcXobNnmeNi4176GYl0EZMK";
		$req .= "&tx=$tx_token&at=$auth_token";
		$header = '';
		$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
		$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
		
		
		if (!$fp) {
		
		} else {
			fputs ($fp, $header . $req);
			
			$res = '';
			$headerdone = false;
			while (!feof($fp)) {
				$line = fgets ($fp, 1024);
				if (strcmp($line, "\r\n") == 0) {
					$headerdone = true;
				}
				else if ($headerdone)
				{
					$res .= $line;
				}
			}

			$lines = explode("\n", $res);

			$keyarray = array();
			if ( $lines[0] == "SUCCESS" ) {

				foreach( $lines as $value ) {
					$ex = explode( '=', $value );
					
					if( isSet( $ex[0] ) && isSet( $ex[1] ) ) {
						$keyarray[$ex[0]] = urldecode( $ex[1] );
					}
				}				

				$orderId = $keyarray['item_name'];
				$currency = $keyarray['mc_currency'];
				
				$Orders = new Orders();
				$item = $Orders->getItemService( $keyarray['item_name'] );
				
				$curr = $item->getFirst()->currency;
				if( trim( $currency ) != trim( $curr ) ) {
					$this->view->notice = false;
				} else {
				
				if( $item = $item->getFirst() ) {
						if($item->vouchers_v_id > 0){
						
						$user = new Users();
						$us = $user->getItemByIdService( $item->vouchers_owner_id );
						if($us) {

							$item->state = 1;
							$item->save();
						
							$Vou = new Vouchers();
						
							$vouchers = $Vou->getItemService( $item->vouchers_v_id );
						
							if( $vouchers = $vouchers->getFirst() ) {
								$vouchers->state = 1;
								$vouchers->save();
							}
							Core_Logs::log('carnauba','platnosci_paypal',"przypisuje voucher: " . $item->vouchers_v_id);
							Core_Logs::log('carnauba','platnosci_paypal',"### end ### ");

						}				
					
					} else {			
					   
						$item->state = 1;
						$item->save();
						
						//
                		// wysylka zalacznika (produkt specjalny)
                		//
                		$orderId = $item->o_id;
                		$userEmail = $item->email;
                		
                		$modelOrdersItems = new OrdersItems;
                		$rowOrderItems = $modelOrdersItems->getItems($orderId)->toArray();

                		if(!empty($userEmail))
                		{
                    		foreach($rowOrderItems As $itemrow)
                    		{
                    		    if($itemrow['special']==1)
                    		    {
                    		        //to jest produkt specjalny
                    		        $modelProductsSpecial = new ProductsSpecial;
                    		        $rowProductSpecial = $modelProductsSpecial->getItem($itemrow['products_p_id'])->toArray();
                                    $attachmentFileName = $rowProductSpecial[0]['attachment'];
                    		        
                                    $content = file_get_contents('./public/uploads/'.$attachmentFileName);
                                    
                    				$mail = new Core_Mail();
                    				
                                	if(!empty($content))
                            	    {
                    					$attachment = $mail->createAttachment( $content );
                    					$attachment->filename = $attachmentFileName;
                    					$bodyHtml = $this->view->translate('mail_ps_body');
                            	    }
                            	    else
                            	    {
                            	        // nie ma pliku z zalacznikiem
                            	        $bodyHtml = $this->view->translate('mail_ps_body_noattach');
                            	    }
                    
                    				$mail->addTo($userEmail);
                    				$mail->setFrom('no-reply@carnauba.pl', 'Carnauba');
                    				$mail->setSubject($this->view->translate('mail_ps_tytul'));
                    				$mail->setBodyHtml($bodyHtml);
                    			    $mail->send();
                    		    }
                    		} 
                		}
                		// koniec wysylka zalacznika (produkt specjalny)

						Core_Logs::log('carnauba','platnosci_paypal',"zmieniam status transakcji: $orderId na zapłacone");
						Core_Logs::log('carnauba','platnosci_paypal',"### end ### ");
					}

				}
				
				$this->view->trinfo = $keyarray;
				
				$this->view->notice = true;
				}
			} else if (strcmp ($lines[0], "FAIL") == 0) {
				$this->view->notice = false;
			}
			
		}
		
		fclose ($fp);	
	}
	
	public function onlineAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();

		$server = 'www.platnosci.pl';
		$server_script = '/paygw/ISO/Payment/get/txt';
		define('PLATNOSCI_POS_ID', 39289);
		define('PLATNOSCI_KEY1', "7f75e9c8584e35913d544090dcc088fa");
		define('PLATNOSCI_KEY2', "50fc7da683903bdb506f0024e0d4ab95");

		Core_Logs::log('carnauba','platnosci',"\n### START POST ###" );
		foreach( $_POST as $key => $value ) {
			Core_Logs::log('carnauba','platnosci', $key . " = " . $value );
		}
		Core_Logs::log('carnauba','platnosci',"### END POST ###\n" );
		
		Core_Logs::log('carnauba','platnosci',"### start ### ");


		if(!isset($_POST['pos_id']) || !isset($_POST['session_id']) || !isset($_POST['ts']) || !isset($_POST['sig'])) {
			Core_Logs::log('carnauba','platnosci', 'ERROR: EMPTY PARAMETERS');
			echo 'OK';
			exit;	
		}

		if ($_POST['pos_id'] != PLATNOSCI_POS_ID)
		{
			Core_Logs::log('carnauba','platnosci_blad',"blad pos_id");
			echo 'OK';
			exit;
		}
		$sig = md5( $_POST['pos_id'] . $_POST['session_id'] . $_POST['ts'] . PLATNOSCI_KEY2);
		if ($_POST['sig'] != $sig)
		{
			Core_Logs::log('carnauba','platnosci_blad',"blad podpisu");
			echo 'OK';
			exit;
		}		
		$ts = time();
		$sig = md5( PLATNOSCI_POS_ID . $_POST['session_id'] . $ts . PLATNOSCI_KEY1);
		$parameters = "pos_id=" . PLATNOSCI_POS_ID . "&session_id=" . $_POST['session_id'] . "&ts=" . $ts . "&sig=" . $sig;

		$fsocket = false;
		$curl = false;
		$result = false;

		if ( (PHP_VERSION >= 4.3) && ($fp = @fsockopen('ssl://' . $server, 443, $errno, $errstr, 30)) ) {
 			$fsocket = true;
		} elseif (function_exists('curl_exec')) {
 			$curl = true;
		}

		if ($fsocket == true) {
 			$header = 'POST ' . $server_script . ' HTTP/1.0' . "\r\n" .
   			'Host: ' . $server . "\r\n" .
   			'Content-Type: application/x-www-form-urlencoded' . "\r\n" .
   			'Content-Length: ' . strlen($parameters) . "\r\n" .
   			'Connection: close' . "\r\n\r\n";
 		@fputs($fp, $header . $parameters);
 		$platnosci_response = '';
 			while (!@feof($fp)) {
  				$res = @fgets($fp, 1024);;
  				$platnosci_response .= $res;
 			}
 		@fclose($fp);
		} elseif ($curl == true) {
 			$ch = curl_init();
 			curl_setopt($ch, CURLOPT_URL, "https://" . $server . $server_script);
 			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
 			curl_setopt($ch, CURLOPT_HEADER, 0);
 			curl_setopt($ch, CURLOPT_TIMEOUT, 20);
 			curl_setopt($ch, CURLOPT_POST, 1);
 			curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
 			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 			$platnosci_response = curl_exec($ch);
 			curl_close($ch);
		} else {

			Core_Logs::log('carnauba','platnosci_blad',"blad metody pobierania danych z platnosci");
			echo 'OK';
			exit;

		}
		
		$ex = explode( "\n", $platnosci_response );
		
		$resArr;
		foreach( $ex as $vx ) {
			$tmp = explode( ':', $vx );
			
			if( isSet( $tmp[0] ) && isSet( $tmp[1] ) ) {
				$resArr[trim( $tmp[0] )] = trim( $tmp[1] );
			}
		}

		if ($resArr['trans_pos_id'] != PLATNOSCI_POS_ID) 
		{
			Core_Logs::log('carnauba','platnosci_blad',"blad pos_id przy sprawdzeniu trans");
			echo 'OK';
			exit;
		}

      	$sig = md5($resArr['trans_pos_id'].$resArr['trans_session_id'].$resArr['trans_order_id'].$resArr['trans_status'].$resArr['trans_amount'].$resArr['trans_desc'].$resArr['trans_ts'].PLATNOSCI_KEY2);

		if($sig != $resArr['trans_sig'])
		{
			Core_Logs::log('carnauba','platnosci_blad',"blad podpisu 2 przy sprawdzeniu trans");
			echo 'OK';
			exit;
		}	
      	
      	switch ($resArr['trans_status']) {
          		case 1: $result =  array('code' => $resArr['trans_status'], 'message' => 'nowa'); break;
          		case 2: $result =  array('code' => $resArr['trans_status'], 'message' => 'anulowana'); break;
          		case 3: $result =  array('code' => $resArr['trans_status'], 'message' => 'odrzucona'); break;
          		case 4: $result =  array('code' => $resArr['trans_status'], 'message' => 'rozpoczęta'); break;
          		case 5: $result =  array('code' => $resArr['trans_status'], 'message' => 'oczekuje na odbiór'); break;
          		case 6: $result =  array('code' => $resArr['trans_status'], 'message' => 'autoryzacja odmowna'); break;
          		case 7: $result =  array('code' => $resArr['trans_status'], 'message' => 'płatność odrzucona'); break;
          		case 99: $result =  array('code' => $resArr['trans_status'], 'message' => 'płatność odebrana - zakończona'); break;
          		case 888: $result =  array('code' => $resArr['trans_status'], 'message' => 'błędny status'); break;
          		default: $result =  array('code' => false, 'message' => 'brak statusu'); break;
  		}

		if ( $result['code'] ) {  //--- rozpoznany status transakcji

    			$pos_id = $resArr['trans_pos_id'];
    			$session_id = $resArr['trans_session_id'];
    			$order_id = $resArr['trans_order_id'];
    			$amount = $resArr['trans_amount'];  //-- w groszach
    			$status = $resArr['trans_status'];
    			$desc = $resArr['trans_desc'];
    			$ts = $resArr['trans_ts'];
    			$sig = $resArr['trans_sig'];
				
    			if ( $result['code'] == '99' ) { 
    								
					$Orders = new Orders();
					
					$item = $Orders->getItemService( $desc );
					
					if( $item = $item->getFirst()) {
					    
					    if( $item->state > 0 ) {
					        Core_Logs::log('carnauba','platnosci',"orderid: $desc");
					        Core_Logs::log('carnauba','platnosci',"### end 222 ### ");
							echo 'OK';
							exit;
					    }
					    
					    //ustawiamy ze zaplacono zamowienie
						$item->state = 1;
						$item->save();
					    
						
						
						//Wysylamy e-mail ze oplacono zamowienie
        				$mail = new Core_Mail();
        				
    				    if($item->vouchers_v_id >0)
    				    {
    				        // nota ksiegowa (bon)
            				$attachment = $mail->createAttachment( file_get_contents( getcwd() . '/public/faktury/bon_' . $item->o_id . '.pdf' ) );
            				$attachment->filename = 'bon_' . $item->o_id . '.pdf';

    				    }
    				    else
    				    {
    				        // faktura vat
            				$attachment = $mail->createAttachment( file_get_contents( getcwd() . '/public/faktury/faktura_' . $item->o_id . '_vat.pdf' ) );
            				$attachment->filename = 'faktura_' . $item->o_id . '_vat.pdf';
    				    }
        				
        				$mail->addTo( $item->email);
        				$mail->setFrom( 'no-reply@carnauba.pl', 'Carnauba' );
        				$mail->setSubject( $this->view->translate( 'ch_state_topic_1' ) );
        				$mail->setBodyHtml( 
        					sprintf( 
        						$this->view->translate( 'ch_state_body_1' ),
        						$item->o_id
        					) 
        				);
        				$mail->send();
					    
						if($item->vouchers_v_id > 0 ){

						    // - aktywacja konta usera jesli to byl nowy user stworzony przy kupowaniu vouchera
							// - wysylanie e-mail
						    $user = new Users();
							$us = $user->getItemByIdService( $item->vouchers_owner_id);
							if($us)
							{
							    $newAccount = false;
							    if($us->state==0)
							    {
							        $newAccount = true; 
							        $newPass = substr(md5(time().rand(1,999)),0,10);
							        $us->pass = md5($newPass);
							        $us->state = 2;
							        $us->save();
							    }
							    
							    //aktywujemy voucher
								$Vou = new Vouchers();
								$vouchers = $Vou->getItemService( $item->vouchers_v_id );
								if( $vouchers = $vouchers->getFirst() ) 
								{
									$vouchers->state = 1;
									$vouchers->save();
								}

                        	    $mail = new Core_Mail();
            					$mail->setFrom( 'no-reply@carnauba.pl', 'Carnauba' );
            					$mail->setSubject( $this->view->translate( 'voulcher_topic' ) );
            					
            					if($newAccount==false)
            					{
            					    $mail->addTo($us->email, $us->name . ' ' . $us->surname );
                					$mail->setBodyHtml( 
                						sprintf( 
                							$this->view->translate( 'voulcher_body' ),
                							$this->_helpSess->formLogged['name'] . ' ' . $this->_helpSess->formLogged['surname'],
                							$vouchers->value
                						) 
                					);
            					}
            					else
            					{
            					    //stworzono nowe konto dla uzytkonika
            					    $mail->addTo( $us->email);
                					$mail->setBodyHtml( 
                						sprintf( 
                							$this->view->translate( 'voulcher_body2' ),
                							$this->_helpSess->formLogged['name'] . ' ' . $this->_helpSess->formLogged['surname'],
                							$vouchers->value,
                							$us->email,
                							$newPass 
                						) 
                					);
            					}
            					
            					$mail->send();


								Core_Logs::log('carnauba','platnosci',"przypisuje voucher: " . $item->vouchers_v_id);
								Core_Logs::log('carnauba','platnosci',"### end ### ");
							}
							
							echo 'OK';
							exit;						
						
						} else {			
							
							//
                    		// jestli w tym zamówieniu byl jakis produkt specjalny to
                    		// wysylka zalacznika z produktem specjalnym
                    		//
                    		$orderId = $item->o_id;
                    		$userEmail = $item->email;
                    		
                    		$modelOrdersItems = new OrdersItems;
                    		$rowOrderItems = $modelOrdersItems->getItems($orderId)->toArray();

                    		if(!empty($userEmail))
                    		{
                        		foreach($rowOrderItems As $itemrow)
                        		{
                        		    if($itemrow['special']==1)
                        		    {
                        		        //to jest produkt specjalny
                        		        $modelProductsSpecial = new ProductsSpecial;
                        		        $rowProductSpecial = $modelProductsSpecial->getItem($itemrow['products_p_id'])->toArray();
                                        $attachmentFileName = $rowProductSpecial[0]['attachment'];
                        		        
                                        $content = file_get_contents('./public/uploads/'.$attachmentFileName);
                                        
                        				$mail = new Core_Mail();
                        				
                                    	if(!empty($content))
                                	    {
                        					$attachment = $mail->createAttachment( $content );
                        					$attachment->filename = $attachmentFileName;
                        					$bodyHtml = $this->view->translate('mail_ps_body');
                                	    }
                                	    else
                                	    {
                                	        // nie ma pliku z zalacznikiem
                                	        $bodyHtml = $this->view->translate('mail_ps_body_noattach');
                                	    }
                        
                        				$mail->addTo($userEmail);
                        				$mail->setFrom('no-reply@carnauba.pl', 'Carnauba');
                        				$mail->setSubject($this->view->translate('mail_ps_tytul'));
                        				$mail->setBodyHtml($bodyHtml);
                        			    $mail->send();
                        		    }
                        		} 
                    		}
                    		// koniec wysylka zalacznika (produkt specjalny)
							
							
							
							Core_Logs::log('carnauba','platnosci',"zmieniam status transakcji: $desc na zapłacone");
							Core_Logs::log('carnauba','platnosci',"### end ### ");

							echo "OK";
							exit;
						}
					} else {
						Core_Logs::log('carnauba','platnosci',"nie znaleziono transakcji o id: $desc");
						Core_Logs::log('carnauba','platnosci',"### end ### ");
					}
    			}
		} else {

    			Core_Logs::log('carnauba','platnosci_blad',"blad statusu");
			echo 'OK';
			exit;
		} 	

		Core_Logs::log('carnauba','platnosci',"### nothing to do end ### ");
		echo 'OK';
		exit;
	}

	public function newsAction() {
		$page = intval( $this->_request->getParam( 'page', 1 ) );
		$type = intval( $this->_request->getParam( 'type', 2 ) );
		
		$typeAllow = array( 1 => true, 2 => true );
		if( !array_key_exists( $type, $typeAllow ) ) {
			$this->_forward( 'index', 'index' );
		}
		$this->view->type = $type;
		$this->view->active = 'index/news/type/' . $type;
		
		$News = new News();
		
		$pager = $News->getListWithPagerService( $type, $page, $this->newsLimit, $this->view->baseUrl() . '/index/news/page/{%page_number}/type/'  );
		
		$pagerLayout = $pager['layout'];
		$pagerLayout->setTemplate('<a class="nums" href="{%url}">{%page}</a>');
		$pagerLayout->setSelectedTemplate('<a class="nums focus" href="{%url}">{%page}</a>');
		
		$pager = $pager['pager'];

		$this->view->list = $pagerLayout->execute();
		$this->view->pager = $pagerLayout;
		
		$this->view->result = $pager->getNumResults();
		$this->view->page = $page;
		$this->view->pathInfo = $this->view->baseUrl() . $this->_request->getPathInfo();
		$this->view->limit = $this->newsLimit;
	}
	
	public function shownewsAction() {
		$this->view->active = 'index/news';

		$id = intval( $this->_request->getParam( 'id', false ) );
		if( $id ) {
			$News = new News();
			$item = $News->getItemService( $id );
			if( $item ) {				
				$this->view->item = $item->getFirst()->toArray();
			} else {
				$this->_forward( 'p404', 'index' );
			}
		} else {
			$this->_forward( 'p404', 'index' );
		}
	}

	public function showstaticAction() {
		$this->view->active = 'index/news';

		$id = intval( $this->_request->getParam( 'id', false ) );
		if( $id ) {
			$News = new News();
			$item = $News->getItemService( $id );
			if( $item ) {				
				$this->view->item = $item->getFirst()->toArray();
			} else {
				$this->_forward( 'p404', 'index' );
			}
		} else {
			$this->_forward( 'p404', 'index' );
		}
	}	
	
	public function searchAction() {
		$q = $this->_request->getParam( 'q', false );
		$adv = $this->_request->getParam( 'adv', false );
		
		$price_from = $this->_request->getParam( 'price_from', false );
		$price_to = $this->_request->getParam( 'price_to', false );
		
		$filterChain = new Zend_Filter();
		$filterChain->addFilter(new Zend_Filter_StripTags())
					->addFilter(new Zend_Filter_StringTrim());

		 
		// Filter the username
		$q = str_replace( '"', '', $filterChain->filter( $q ) );
		$q = str_replace( '\'', '', $filterChain->filter( $q ) );

		$Products = new Products();

		$page = intval( $this->_request->getParam( 'page', 1 ) );
		$parent = intval( $this->_request->getParam( 'p', 0 ) );
		$sort = $this->_request->getParam( 'sort', 'price' );
		$sort_direction = strtolower( $this->_request->getParam( 'sd', 'asc' ) );

		$this->view->q = $q;
		$this->view->adv = $adv;
		$this->view->sort = $sort;
		$this->view->sort_direction = $sort_direction;
		$this->view->parent = $parent;
		$this->view->price_from = $price_from;
		$this->view->price_to = $price_to;
		
		if( $adv ) {
			
			$Categries = new Categries();
			$this->view->categories = $Categries->getListService( 0, $this->locale );
			
			$Manufacturers = new Manufacturers();
			$this->view->manufacturers = $Manufacturers->getListService();

		}

		$categoriesFiltr = $this->_request->getParam( 'c', false );
		$manufacturesFiltr = $this->_request->getParam( 'm', false );
		$priceFrom = $this->_request->getParam( 'price_from', false );
		$priceTo = $this->_request->getParam( 'price_to', false );

		$this->view->categoriesFiltr = ( $categoriesFiltr ) ? $categoriesFiltr : array();
		$this->view->manufacturesFiltr = ( $manufacturesFiltr ) ? $manufacturesFiltr : array();
		$this->view->isPost = true;

		if( 
			$adv && 
			!$q && 
			!$categoriesFiltr &&
			!$manufacturesFiltr
		) {
			$this->view->isPost = false;
		} else {
			if( !$this->userData ) {
				$pager = $Products->searchWithPagerService( array(
					'q' => $q,
					'categories' => $categoriesFiltr,
					'manufactures' => $manufacturesFiltr
				), array(
					'r1' => 'yes'
				), false, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit, $adv, $price_from, $price_to );
			} else {
				$sess = new Zend_Session_Namespace( 'ranks' );
				
				if( count( $sess->data ) > 0 ) {
					$pager = $Products->searchWithPagerService( array(
						'q' => $q,
						'categories' => $categoriesFiltr,
						'manufactures' => $manufacturesFiltr
					), false, $sess->data, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit, $adv, $price_from, $price_to  );
				} else {
					$pager = $Products->searchWithPagerService( array(
						'q' => $q,
						'categories' => $categoriesFiltr,
						'manufactures' => $manufacturesFiltr
					), array(
						'r1' => 'yes'
					), false, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit, $adv, $price_from, $price_to  );
				}
			}
			
			if( $pager ) {
			
				$pagerLayout = $pager['layout'];
				$pagerLayout->setTemplate('<a class="nums" href="{%url}">{%page}</a>');
				$pagerLayout->setSelectedTemplate('<a class="nums focus" href="{%url}">{%page}</a>');
				
				$pager = $pager['pager'];
		
				$this->view->list = $pagerLayout->execute();
				$this->view->pager = $pagerLayout;
				
				$this->view->result = $pager->getNumResults();
				$this->view->page = $page;
				$this->view->pathInfo = $this->view->baseUrl() . $this->_request->getPathInfo();
				$this->view->limit = $this->itemsLimit;
			
			} else {
				$this->view->emptyResult = true;
			} 
		
		}
	}

	public function staticAction() {
	}

	public function confirmAction() {
		$userId = $this->_request->getParam( 'u', false );
		
		$this->view->confirmStatus = false;
		
		if( $userId ) {
			$Users = new Users();
			$userId = base_convert( $userId, 32, 10 );
			$item = $Users->getItemByIdService( $userId );
			if( $item ) {
				if( $item->state == 0 ) {
					$item->state = 2;
					$item->save();
					$this->view->confirmStatus = true;
				}
			}
		}

	}

	public function newaccountAction() {
		$agentId = intval( $this->_getParam( 'u', 0 ) );
		$sugEmail = $this->_getParam( 'm', false );

		$this->view->agentId = $agentId;
		$this->view->email = $sugEmail;
		
		if( $this->_request->isPost() ) {
			//Core_Debug::pr($this->_request->getPost());die();
			$Users = new Users();

			$post = $this->_request->getPost();
			
			$item = $Users->getItemByEmailService( $post['email'] );
			
			if( $item ) {
				$this->view->error_email = true;
			}
			if(empty($post['pass'])){
			    $this->view->pass_empty = true;
			}
			
			if($post['pass'] != $post['password_retype']){
			    $this->view->pass_retypeinvalid = true;
			}
			
			foreach( $post as $key => $value ) {
				if( !in_array( $key, array(
					'rules', 'rules2', 'pass', 'password_retype', 'birthday_day', 'birthday_month', 'birthday_year'
				) ) && !$this->view->error_email ) {
					$Users->{$key} = $value;
				}

				$this->view->{$key} = $value;
			}
			
			if( !$this->view->error_email && !$this->view->pass_empty && 
			    !$this->view->pass_retypeinvalid) 
		    {
				$Users->state = ( $post['parent_u_id'] > 0 ) ? 2 : 0;
				$Users->role = 1;
				$Users->registration_date = Date( 'Y-m-d H:i:s' );
				$Users->pass = md5( $post['pass'] );
				$Users->langs_l_id = Doctrine_Core::getTable('Langs')->findOneByIden( $this->locale )->l_id;
				$Users->save();

				if( $Users->u_id ) {
					if( !$post['parent_u_id'] ) {
						
						$this->view->regok = true;
						
						$mail = new Core_Mail();
						$mail->addTo( $post['email'], $post['name'] . ' ' . $post['surname'] );
						$mail->setFrom( 'no-reply@carnauba.pl', 'Carnauba' );
						$mail->setSubject( $this->view->translate( 'reg_topic' ) );
						$mail->setBodyHtml( sprintf( $this->view->translate( 'reg_body' ), $this->serverName . $this->view->baseUrl() . '/index/confirm/u/' . base_convert( $Users->u_id, 10, 32 ) ) );
						$mail->send();
					} else {
						$this->view->regok2 = true;
					}
				}
			}
		}
	}

	public function remindpassAction() {
		$md5 = $this->_request->getParam( 'u', false );
		$email = $this->_request->getParam( 'e', false ); 
		
		$sec = 'wspołczynnik-dobroci-mega-taje-cos-37dg26roshhsik7roes562gr';
		
		if( $md5 && $email ) {
			$this->view->remindSendStatus = false;
			$Users = new Users();
			$item = $Users->getItemByEmailService( $email );
			if( $item ) {
				if( md5( $item->email . $sec ) == $md5 ) {
					$pass = substr(md5(date("d.m.Y.H.i.s").rand(1,1000000)) , 0 , 10);

					$item->pass = md5( $pass );
					$item->save();

					$this->view->remindSendStatus = true;
					
					$mail = new Core_Mail();
					$mail->addTo( $item->email, $item->name . ' ' . $item->surname );
					$mail->setFrom( 'no-reply@carnauba.pl', 'Carnauba' );
					$mail->setSubject( $this->view->translate( 'remind_topic' ) );
					$mail->setBodyHtml( sprintf( $this->view->translate( 'remind_success_body' ), $pass ) );
					$mail->send();
				}
			}
			
		} else {
		
			if( $this->_request->isPost() ) {
				
				$this->view->remindStatus = false;
				
				$post = $this->_request->getPost();
				
				$Users = new Users();
				$item = $Users->getItemByEmailService( $post['email'] );
				
				if( $item ) {
				
					$this->view->remindStatus = true;

					
					$url = $this->serverName . $this->view->baseUrl() . '/index/remindpass/u/' . md5( $post['email'] . $sec ) . '/e/' . $post['email'];
			
					$mail = new Core_Mail();
					$mail->addTo( $item->email, $item->name . ' ' . $item->surname );
					$mail->setFrom( 'no-reply@carnauba.pl', 'Carnauba' );
					$mail->setSubject( $this->view->translate( 'remind_topic' ) );
					$mail->setBodyHtml( sprintf( $this->view->translate( 'remind_body' ), $url ) );
					$mail->send();
				}
			}
		}
	}
	
	public function loginAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();

		Core_Logs::log( 'carnauba', 'login', 'login: ' . $this->_getParam('login') . ', pass: ' . $this->_getParam('password') );
		
		if( $this->_request->isPost() ) {
			$adapter = new Core_Auth_Adapter( $this->_getParam('login'), $this->_getParam('password') );
			$result = Zend_Auth::getInstance()->authenticate($adapter);
			if( Zend_Auth::getInstance()->hasIdentity() ) {
				if( $this->_getParam('json') )  {
					echo Zend_Json::encode(array(
						'status' => true
					));
				} else {
					echo "result=1&name=" . Zend_Auth::getInstance()->getIdentity()->name;
				}
			} else {
				if( $this->_getParam('json') )  {
					echo Zend_Json::encode(array(
						'status' => false
					));
				} else {
					echo "result=0&name=";
				}
			}
		}
	}
	
	public function newsletterAction() {
		if( $this->_request->isPost() ) {
			
			$post = $this->_request->getPost();
			
			if( filter_var( $post['email'], FILTER_VALIDATE_EMAIL ) ) {
				$Newsletter = new Newsletter();
				$Newsletter->email = $post['email'];
				$Newsletter->lang = $this->locale;
				$Newsletter->save();
				$this->view->returnurl = $post['returnurl'];
			} else {
				$this->view->error_newsletter = true;
				$this->_redirect($post['returnurl']);
			}
		} else {
			$this->_forward( 'index', 'index' );
		}
	}
	
	public function accountAction() {
		$ref = isSet( $_GET['ref'] ) ? $_GET['ref'] : '';
		$this->view->ref = $this->view->baseUrl() . '/' . $ref;
	}
	
	public function logoutAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
    	Zend_Auth::getInstance()->clearIdentity();
    	
    	$sess = new Zend_Session_Namespace( 'ranks' );
    	$sess->unsetAll();
    	
    	$nored = $this->_request->getParam( 'nored', 0 );
    	
    	if( !$nored ) {
    		$this->_redirect('/index');
    	} else {
    		echo 'result=1';
    	}
	}
	
	private function _loc2act( $locale ) {
		switch( $locale ) {
			case 'pl' :
				return 0;
			case 'en' :
				return 1;
			case 'cs' : 
				return 2;
		}
	}
	public function sendAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		$newsletter = new Newsletter();
		$newsletterqueue = new NewsletterQueue();
		
		//ilość wysyłanych maili na raz
		$ilosc = 20;
		
		$aktywne = $newsletterqueue->getItemBySent('no');
		if(get_class($aktywne))
		{
			//wysyłaj maile
			$mail = new Core_Mail();
			$mail->setFrom( 'no-reply@carnauba.pl', 'Carnauba' );
			$mail->setSubject( 'Newsletter');
			$api_user = new Users();
			switch($aktywne->type)
			{
				case 'new':
					$users = $newsletter->getItem($aktywne->last_u_id );
					break;
				case 'all':
					$users = $api_user->getItems($aktywne->last_u_id );
					break;
				case 'ran':
					$users = $api_user->getItemsByRank($aktywne->last_u_id , $aktywne->rank);
					break;
			}
			foreach($users as $user)
			{
				if(!$ilosc)
					break;
				$body = 'body_'.$user->lang;
				$mail->setBodyHtml($aktywne->$body);
				$mail->addTo( $user->email, '' );
				$mail->send();
				$aktywne->last_u_id = ($aktywne->type=='new') ? $user->n_id : $user->u_id;
				$ilosc--;
			}
			if($ilosc)
			{
				$aktywne->sent = 'yes';
			}
			$aktywne->save();
		}
	}

}

